package com.sh.sales.happysales.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.sh.polymedicine.happysale.result.SimpleResult;
import com.sh.polymedicine.happysale.result.UserInfoResult;
import com.sh.polymedicine.happysale.service.envelop.HappySaleManager;
import com.sh.sales.happysales.R;
import com.sh.sales.happysales.app.AppData;
import com.sh.sales.happysales.app.utils.LoginOutUtil;
import com.sh.sales.happysales.base.BaseActivity;
import com.sh.sales.happysales.datautils.LocalUserInfoUtils;
import com.sh.sales.happysales.imgutil.LoadImageManager;
import com.sh.sales.happysales.service.LoginObsever;
import com.sh.sales.happysales.view.AutoTextView;
import com.sh.sales.happysales.view.NewToast;
import com.sh.sales.happysales.view.RoundCornersImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;
import rx.Subscriber;

/**
 * Created by zhouyucheng on 2017/9/15.
 */

public class UserInfoActivity extends BaseActivity implements LoginObsever, EasyPermissions.PermissionCallbacks {
    private String TAG = "UserInfoActivity";
    @BindView(R.id.set_back)
    ImageView setBack;
    @BindView(R.id.info_sure)
    TextView infoSure;
    @BindView(R.id.info_picture)
    RoundCornersImageView infoPicture;
    @BindView(R.id.info_nick)
    LinearLayout infoNick;
    @BindView(R.id.info_location)
    LinearLayout infoLocation;
    @BindView(R.id.info_name)
    LinearLayout infoName;
    @BindView(R.id.info_phone)
    LinearLayout infoPhone;
    @BindView(R.id.info_position)
    LinearLayout infoPosition;

    @BindView(R.id.info_sacn2)
    TextView infosacn2;
    @BindView(R.id.view)
    View view;

    @BindView(R.id.text_nick)
    TextView textnick;
    @BindView(R.id.text_region)
    TextView textregion;
    @BindView(R.id.text_name)
    TextView textname;
    @BindView(R.id.text_mobile)
    TextView textmobile;
    @BindView(R.id.text_role)
    TextView textrole;

    @BindView(R.id.lin_sale_manger)
    LinearLayout linsalemanger;
    @BindView(R.id.text_roleleft)
    TextView textroleleft;

    @BindView(R.id.info_role_enter)
    ImageView inforoleenter;

    //    @BindView(R.id.my_manager)
//    LinearLayout mymanager;
//    @BindView(R.id.my_manager_text)
//    TextView mymanagertext;
    private Bitmap head;// 头像Bitmap
    /**
     * 头像文件名称
     */
    private File file;
    /**
     * 头像路径
     */
    @SuppressLint("SdCardPath")
    private static String path = "/sdcard/myHead/";// sd路径
    private DisplayImageOptions options;
    private UserInfoResult mUserInfoResult;
    private Subscriber<SimpleResult> changePicSubscriber;
    private String userSign;

    private String manegerCode;
    private int refreshUserSignTag = -1;
    private PopupWindow bindPopupWindow;
    private static final int MY_PERMISSIONS_REQUEST_PAIZHAO = 1;
    private static final int MY_PERMISSIONS_REQUEST_BENDITUXIANG = 2;
    private static final int MY_PERMISSIONS_REQUEST_CUT = 3;
    private static final int MY_PERMISSIONS_REQUEST_ZING = 4;
    private PopupWindow headPopupWindow;
    private String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
            , Manifest.permission.CAMERA};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_useinfo);
        ButterKnife.bind(this);
        mAppManager.addActivity(this);
        mLoginObserable.registerObserver(this);
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.icon_nologin)
                .showImageForEmptyUri(R.drawable.icon_nologin)
                .displayer(new RoundedBitmapDisplayer(4))
                .showImageOnFail(R.drawable.icon_nologin)
                .imageScaleType(ImageScaleType.EXACTLY)
                .considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        perms = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
                , Manifest.permission.CAMERA};
        init();
    }

    private void init() {
        initUi();
        switch (Integer.parseInt(mUserInfoResult.getRole())) {
            case -1:
                //信息未完善
                break;
            case 0:
                linsalemanger.setVisibility(View.GONE);
                infoPosition.setVisibility(View.VISIBLE);
                textroleleft.setText("我的销售经理");
                textrole.setText("扫一扫成为销售员");
                inforoleenter.setVisibility(View.VISIBLE);
                infosacn2.setText("扫一扫成为销售员");
                break;
            case 1:
                linsalemanger.setVisibility(View.GONE);
                infoPosition.setVisibility(View.VISIBLE);
                textroleleft.setText("人物属性");
                textrole.setText("商户");
                inforoleenter.setVisibility(View.GONE);
                infosacn2.setText("已经成为商户");
                break;
            case 2:
                linsalemanger.setVisibility(View.VISIBLE);
                infoPosition.setVisibility(View.GONE);
                infosacn2.setText("已经成为销售经理");
                break;
            case 3:
                linsalemanger.setVisibility(View.GONE);
                infoPosition.setVisibility(View.VISIBLE);
                textroleleft.setText("人物属性");
                textrole.setText("销售员");
                inforoleenter.setVisibility(View.VISIBLE);
                infosacn2.setText("已经是销售员");
//                mymanager.setVisibility(View.VISIBLE);
//                mymanagertext.setText(mUserInfoResult.);
                break;
        }

    }

    private void initUi() {
        mUserInfoResult = AppData.getInstence().getmUserInfoResult();
        userSign = AppData.getInstence().getmUserToken().getUserSign();
        mLoadImageManager.displayImage(mUserInfoResult.getPortrait(), infoPicture, LoadImageManager.IMG, options);
        textnick.setText(mUserInfoResult.getNickname());
        textregion.setText(mUserInfoResult.getRegionName());
        textname.setText(mUserInfoResult.getRealName());
        textmobile.setText(mUserInfoResult.getMobile());
    }

    @OnClick({R.id.set_back, R.id.info_sure, R.id.lin_sale_manger, R.id.info_picture, R.id.info_nick, R.id.info_location, R.id.info_name, R.id.info_phone, R.id.info_position, R.id.info_sacn2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.set_back:
                mAppManager.finishActivity(this);
                break;
            case R.id.info_sure:
                break;
            case R.id.info_picture:
                showPopupWindow();
                break;
            case R.id.info_nick:
                startActivityForResult(new Intent(UserInfoActivity.this, ChangeNickActivity.class), 8);
                break;
            case R.id.info_location:
                startActivityForResult(new Intent(UserInfoActivity.this, RegionActivity.class), 5);
                break;
            case R.id.info_name:
                break;
            case R.id.info_phone:
                startActivityForResult(new Intent(UserInfoActivity.this, SwichPhNumActivity.class), 6);
                break;
            case R.id.info_position:
            case R.id.info_sacn2:
            case R.id.lin_sale_manger:
                if (EasyPermissions.hasPermissions(UserInfoActivity.this, perms)) {//检查是否获取该权限
                    scanZing();
                } else {
                    EasyPermissions.requestPermissions(UserInfoActivity.this, "必要的权限", MY_PERMISSIONS_REQUEST_ZING, perms);
                }
                break;
        }
    }

    private void scanZing() {
        switch (Integer.parseInt(mUserInfoResult.getRole())) {
            case -1:
            case 0:
                startActivityForResult(new Intent(UserInfoActivity.this, CaptureActivity.class), 7);
                break;
            case 1:
                break;
            case 2:
                myZineShow();
                break;
            case 3:
                break;
        }
    }

    private void myZineShow() {
        Intent m = new Intent();
        m.setClass(UserInfoActivity.this, MyZingActivity.class);
        startActivity(m);
    }


    private void showPopupWindow() {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(UserInfoActivity.this).inflate(
                R.layout.pop_window, null);
        headPopupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        // 设置按钮的点击事件
        RelativeLayout button_pai = (RelativeLayout) contentView
                .findViewById(R.id.pop_rl_photograph);
        button_pai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (EasyPermissions.hasPermissions(UserInfoActivity.this, perms)) {//检查是否获取该权限
                    Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//判断是否是AndroidN以及更高的版本
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        intent2.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                        File file = Environment.getExternalStorageDirectory();
                        File newFile = new File(file, "head.jpg");
                        Uri contentUri = FileProvider.getUriForFile(UserInfoActivity.this.getApplicationContext(), "com.sh.sales.happysales.fileProvider", newFile);
                        intent2.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
                    } else {
                        intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "head.jpg")));
                    }
                    startActivityForResult(intent2, 2);// 采用ForResult打开
                    headPopupWindow.dismiss();
                } else {
                    EasyPermissions.requestPermissions(UserInfoActivity.this, "必要的权限", MY_PERMISSIONS_REQUEST_PAIZHAO, perms);
                }
            }
        });
        RelativeLayout button_xiang = (RelativeLayout) contentView
                .findViewById(R.id.pop_rl_photo_album);
        button_xiang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (EasyPermissions.hasPermissions(UserInfoActivity.this, perms)) {//检查是否获取该权限
                    Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                    intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent1, 1);
                    headPopupWindow.dismiss();
                } else {
                    EasyPermissions.requestPermissions(UserInfoActivity.this, "必要的权限", MY_PERMISSIONS_REQUEST_BENDITUXIANG, perms);
                }
            }
        });
        RelativeLayout photo_cancle = (RelativeLayout) contentView.findViewById(R.id.pop_rl_photo_cancle);
        photo_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                headPopupWindow.dismiss();
            }
        });
        headPopupWindow.setTouchable(true);
        headPopupWindow.setTouchInterceptor(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        headPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.color.tranceparent));
        headPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                headPopupWindow.dismiss();
            }
        });
//		popupWindow.showAsDropDown(view, 0, 140);
        headPopupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    cropPhoto(data.getData());
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    cropPhoto(null);
                }
                break;
            case 3:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    head = extras.getParcelable("data");
                    if (head != null) {
                        /**
                         * 上传服务器代码
                         */
                        setPicToView(head);// 保存在SD卡中
                        setImagHead(head);
                    }
                }
                break;
            case 5://修改区域返回
                if (data != null) {
                    String regionId = data.getStringExtra("change01");
                    String regionName = data.getStringExtra("change02");
                    textregion.setText(regionName);
                    LocalUserInfoUtils.updataUserInfoResult(mUserInfoResult, mUserInfoResult.getInfoId());
                }
                break;
            case 6:
                if (data != null) {
                    String phNum = data.getStringExtra("phNum");
                    textmobile.setText(phNum);
                }
                break;
            case 7:
                if (data != null) {
                    manegerCode = data.getStringExtra("manegerCode");
                    getMangerInfo(manegerCode);
                }
                break;
            case 8:
                if (data != null) {
                    String nickName = data.getStringExtra("nickName");
                    textnick.setText(nickName);
                    break;
                }

        }
    }

    private Subscriber<UserInfoResult> manegerInfoSubscriber;

    /**
     * 通过二维码返回值查找经理信息
     */
    private void getMangerInfo(final String manegerCode) {
        refreshUserSignTag = 2;
        if (manegerInfoSubscriber != null) {
            if (manegerInfoSubscriber.isUnsubscribed()) {
                manegerInfoSubscriber.unsubscribe();
            }
        }
        manegerInfoSubscriber = new Subscriber<UserInfoResult>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: "+e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())) {
                    String message = e.getCause().getCause().getMessage();
                    NewToast.makeText(UserInfoActivity.this, message);
                    int ret =Integer.valueOf( e.getCause().getMessage()) ;
                    if (ret>=100&&ret<200){
                        LoginOutUtil.logOut(UserInfoActivity.this);
                    }
                } else if (HappySaleManager.DATA_NULL.equals(e.getMessage())) {
                    NewToast.makeText(UserInfoActivity.this, e.getCause().getMessage());
                } else {
                    NewToast.makeText(UserInfoActivity.this, "查询经理信息失败，请检查网络");
                }
            }

            @Override
            public void onNext(UserInfoResult userInfoResult) {
                if (!"2".equals(userInfoResult.getRole())) {
                    NewToast.makeText(UserInfoActivity.this, "当前扫码不是销售经理无法绑定哦！");
                } else {
                    showMangerInfo(userInfoResult, manegerCode);
                }
            }
        };
        mHappySaleManager.userInfo(manegerCode, userSign, manegerInfoSubscriber).subscribe(manegerInfoSubscriber);
    }

    private void showMangerInfo(UserInfoResult managerInfo, final String manegerCode) {
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(UserInfoActivity.this).inflate(
                R.layout.pop_mangerinfo, null);
        contentView.setFocusable(true); // 这个很重要
        bindPopupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        // 设置按钮的点击事件
        bindPopupWindow.setTouchable(true);
        ImageView manBack = (ImageView) contentView.findViewById(R.id.man_back);
        AutoTextView bindInfo = (AutoTextView) contentView.findViewById(R.id.man_bindtext);
        bindInfo.setText("  " + "您确定要绑定销售经理" + managerInfo.getRealName() + "（手机号为" + managerInfo.getMobile() + ")旗下的销售员吗？");
        Button manBindCancle = (Button) contentView.findViewById(R.id.man_bt_back);
        Button manBind = (Button) contentView.findViewById(R.id.man_bind);
        manBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NewToast.makeText(UserInfoActivity.this, "取消绑定");
                bindPopupWindow.dismiss();
            }
        });
        manBindCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NewToast.makeText(UserInfoActivity.this, "取消绑定");
                bindPopupWindow.dismiss();
            }
        });
        manBind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popBinMnager(manegerCode, bindPopupWindow);
            }
        });
        bindPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                NewToast.makeText(UserInfoActivity.this, "取消绑定");
                bindPopupWindow.dismiss();
                return false;
            }
        });
        bindPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.color.tranceparent));
        bindPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                bindPopupWindow.dismiss();
            }
        });
        bindPopupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    private Subscriber<SimpleResult> bindSubscriber;

    /**
     * 看了销售经理的信息后绑定
     */
    private void popBinMnager(String manegerCode, final PopupWindow popupWindow) {
        refreshUserSignTag = 3;
        if (bindSubscriber != null) {
            if (bindSubscriber.isUnsubscribed()) {
                bindSubscriber.unsubscribe();
            }
        }
        bindSubscriber = new Subscriber<SimpleResult>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: "+e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())) {
                    String message = e.getCause().getCause().getMessage();
                    NewToast.makeText(UserInfoActivity.this, message);
                    int ret =Integer.valueOf( e.getCause().getMessage()) ;
                    if (ret>=100&&ret<200){
                        LoginOutUtil.logOut(UserInfoActivity.this);
                    }
                } else if (HappySaleManager.DATA_NULL.equals(e.getMessage())) {
                    NewToast.makeText(UserInfoActivity.this, e.getCause().getMessage());
                } else {
                    NewToast.makeText(UserInfoActivity.this, "绑定经理失败，请检查网络");
                }
            }

            @Override
            public void onNext(SimpleResult result) {
                mUserInfoResult.setRole(3 + "");
                mUserInfoResult.setRoleName("销售员");
                LocalUserInfoUtils.updataUserInfoResult(mUserInfoResult, mUserInfoResult.getInfoId());
                textroleleft.setText("人物属性");
                textrole.setText("销售员");
                infosacn2.setText("已经成为销售员");
                popupWindow.dismiss();
            }
        };
        mHappySaleManager.bindManager(manegerCode, userSign, bindSubscriber).subscribe(bindSubscriber);
    }

    @SuppressLint("SdCardPath")
    private void setImagHead(final Bitmap head) {
        refreshUserSignTag = 1;
        String picStr = bitmaptoString(head);

        if (changePicSubscriber != null) {
            if (changePicSubscriber.isUnsubscribed()) {
                changePicSubscriber.unsubscribe();
            }
        }
        changePicSubscriber = new Subscriber<SimpleResult>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                Log.i(TAG, "onError: "+e);
                if (HappySaleManager.DATA_FAIL.equals(e.getMessage())) {
                    String message = e.getCause().getCause().getMessage();
                    NewToast.makeText(UserInfoActivity.this, message);
                    int ret =Integer.valueOf( e.getCause().getMessage()) ;
                    if (ret>=100&&ret<200){
                        LoginOutUtil.logOut(UserInfoActivity.this);
                    }
                } else if (HappySaleManager.DATA_NULL.equals(e.getMessage())) {
                    NewToast.makeText(UserInfoActivity.this, e.getCause().getMessage());
                } else {
                    NewToast.makeText(UserInfoActivity.this, "更换头像失败，请检查网络");
                }
            }

            @Override
            public void onNext(SimpleResult result) {
                infoPicture.setImageBitmap(head);
                mUserInfoResult.setPortrait(result.getPortrait());
                LocalUserInfoUtils.updataUserInfoResult(mUserInfoResult, "1");
            }
        };
        mHappySaleManager.updatePortrait(picStr, userSign, changePicSubscriber).subscribe(changePicSubscriber);
    }

    /**
     * 调用系统的裁剪
     */
    public void cropPhoto(Uri mUri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        Uri uri = null;
        if (null == mUri) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            if (EasyPermissions.hasPermissions(UserInfoActivity.this, perms)) {
                File file = Environment.getExternalStorageDirectory();
                File newFile = new File(file, "head.jpg");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    uri = FileProvider.getUriForFile(UserInfoActivity.this.getApplicationContext(), "com.sh.sales.happysales.fileProvider", newFile);
                } else {
                    uri = Uri.fromFile(newFile);
                }
            } else {
                EasyPermissions.requestPermissions(UserInfoActivity.this, "必要的权限", MY_PERMISSIONS_REQUEST_CUT, perms);
            }
        } else {
            uri = mUri;
        }
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);

    }

    private void setPicToView(Bitmap mBitmap) {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            return;
        }
        FileOutputStream b = null;
        file = new File(path);
        file.mkdirs();// 创建文件夹
        String fileName = path + "head.jpg";// 图片名字
        Log.i("MySelfAccounttActivity", "图片路径==>" + fileName);
        try {
            b = new FileOutputStream(fileName);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (b != null) {
                    // 关闭流
                    b.flush();
                    b.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * // 将Bitmap转换成字符串  压缩20%
     *
     * @param bitmap
     * @return
     */
    public String bitmaptoString(Bitmap bitmap) {
        String string = null;
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, bStream);
        byte[] bytes = bStream.toByteArray();
        string = Base64.encodeToString(bytes, Base64.NO_WRAP);
        return string;
    }


    @Override
    protected void onDestroy() {
        mLoginObserable.unregisterObserver(this);
        super.onDestroy();
    }

    @Override
    public void refreshUserSign(int Position) {
        userSign = AppData.getInstence().getmUserToken().getUserSign();
        switch (refreshUserSignTag) {
            case 1:
                setImagHead(head);
                break;
            case 2:
                getMangerInfo(manegerCode);
                break;
            case 3:
                popBinMnager(manegerCode, bindPopupWindow);
                break;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        //把申请权限的回调交由EasyPermissions处理
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, UserInfoActivity.this);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_PAIZHAO:
                Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent2.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    File file = Environment.getExternalStorageDirectory();
                    File newFile = new File(file, "head.jpg");
                    Uri contentUri = FileProvider.getUriForFile(UserInfoActivity.this.getApplicationContext(), "com.sh.sales.happysales.fileProvider", newFile);
                    intent2.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
                } else {
                    intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "head.jpg")));
                }
                startActivityForResult(intent2, 2);// 采用ForResult打开
                headPopupWindow.dismiss();
                break;
            case MY_PERMISSIONS_REQUEST_BENDITUXIANG:
                Intent intent1 = new Intent(Intent.ACTION_PICK, null);
                intent1.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent1, 1);
                headPopupWindow.dismiss();
                break;
            case MY_PERMISSIONS_REQUEST_CUT:
                cropPhoto(null);
                break;
            case MY_PERMISSIONS_REQUEST_ZING:
                scanZing();
                break;
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

        EasyPermissions.requestPermissions(this, "必要的权限", MY_PERMISSIONS_REQUEST_BENDITUXIANG, String.valueOf(perms));
    }
}
